import 'dart:io';

import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';

/// FileName native_channel
///
/// @Author lax
/// @Date 2024/3/4
///
/// @Description

class NativeChannel {
  static String defaultChannel = 'channel';

  static String defaultOpenUrlMethod = 'openUrl';
  static String defaultCanOpenUrlMethod = 'canOpenUrl';

  static Future<bool> canOpenUrl(String? url) async {
    if (url == null || url == '') {
      return false;
    }
    final uri = Uri.tryParse(url);
    if (uri == null) {
      return false;
    }
    if (Platform.isIOS) {
      final res = await MethodChannel(defaultChannel)
          .invokeMethod(defaultCanOpenUrlMethod, url);
      return res;
    } else {
      return await canLaunchUrl(uri);
    }
  }

  /// 跳转外部链接
  static Future<bool> openUrl(
    String? url, {
    inApp = false,
  }) async {
    if (url == null || url == '') {
      return false;
    }
    final uri = Uri.tryParse(url);
    if (uri == null) {
      return false;
    }
    if (inApp) {
      final res = await canLaunchUrl(uri);
      if (res) {
        return launchUrl(Uri.parse(url));
      }
    } else {
      if (Platform.isIOS) {
        final res = await MethodChannel(defaultChannel)
            .invokeMethod(defaultOpenUrlMethod, Uri.encodeFull(url));
        return res;
      } else {
        final res = await canLaunchUrl(uri);
        if (res) {
          return launchUrl(Uri.parse(url),
              mode: LaunchMode.externalApplication);
        }
      }
    }
    return false;
  }
}
